package cn.stylefeng.guns.modular.business.frequency.orderpick.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.base.entity.BaseEntity;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.custom.enums.*;
import cn.stylefeng.guns.modular.business.frequency.banner.config.activityMq.Producer;
import cn.stylefeng.guns.modular.business.frequency.cmcompany.mapper.CmCompanyMapper;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.entity.CmCompanyOrder;
import cn.stylefeng.guns.modular.business.frequency.cmcompanyorder.mapper.CmCompanyOrderMapper;
import cn.stylefeng.guns.modular.business.frequency.cmdriver.mapper.CmDriverMapper;
import cn.stylefeng.guns.modular.business.frequency.cmlinkman.mapper.CmLinkmanMapper;
import cn.stylefeng.guns.modular.business.frequency.finance.entity.Finance;
import cn.stylefeng.guns.modular.business.frequency.finance.mapper.FinanceMapper;
import cn.stylefeng.guns.modular.business.frequency.financedetail.entity.FinanceDetail;
import cn.stylefeng.guns.modular.business.frequency.financedetail.mapper.FinanceDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderbonus.entity.OrderBonus;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.entity.OrderCarVerify;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.mapper.OrderCarVerifyMapper;
import cn.stylefeng.guns.modular.business.frequency.ordercarverify.service.OrderCarVerifyService;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.entity.OrderModifyDetail;
import cn.stylefeng.guns.modular.business.frequency.ordermodifydetail.mapper.OrderModifyDetailMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.entity.OrderPick;
import cn.stylefeng.guns.modular.business.frequency.orderpick.enums.OrderPickExceptionEnum;
import cn.stylefeng.guns.modular.business.frequency.orderpick.mapper.OrderPickMapper;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.OrderPickParam;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickCarExcludeDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickDTO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.param.PickRecordContractVO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.result.PickOrderVO;
import cn.stylefeng.guns.modular.business.frequency.orderpick.model.result.PkgOrderPick;
import cn.stylefeng.guns.modular.business.frequency.orderpick.service.OrderPickService;
import cn.stylefeng.guns.modular.business.frequency.orderpickfree.entity.OrderPickFree;
import cn.stylefeng.guns.modular.business.frequency.orderpickfree.mapper.OrderPickFreeMapper;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.entity.OrderStatusChange;
import cn.stylefeng.guns.modular.business.frequency.orderstatuschange.service.OrderStatusChangeService;
import cn.stylefeng.guns.modular.business.frequency.orderstock.entity.OrderStock;
import cn.stylefeng.guns.modular.business.frequency.orderstock.mapper.OrderStockMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.entity.OrderSub;
import cn.stylefeng.guns.modular.business.frequency.ordersub.mapper.OrderSubMapper;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgPick;
import cn.stylefeng.guns.modular.business.frequency.ordersub.service.OrderSubService;
import cn.stylefeng.guns.modular.business.frequency.syssite.entity.SysSite;
import cn.stylefeng.guns.modular.business.frequency.syssite.mapper.SysSiteMapper;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.BaseUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
// import com.sun.jmx.snmp.SnmpUnknownAccContrModelException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 提车记录表 服务实现类
 *
 * @author yujie
 * @date 2023/05/09 17:16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderPickServiceImpl extends ServiceImpl<OrderPickMapper, OrderPick> implements OrderPickService {
    @Autowired
    private BusinessUtil businessUtil;
    @Autowired
    private OrderSubMapper orderSubMapper;
    @Autowired
    private OrderSubService orderSubService;
    @Autowired
    private CmDriverMapper driverMapper;
    @Autowired
    private OrderStatusChangeService orderStatusChangeService;
    @Autowired
    private CmLinkmanMapper linkmanMapper;
    @Autowired
    private OrderPickFreeMapper orderPickFreeMapper;
    @Autowired
    private OrderStockMapper orderStockMapper;
    @Autowired
    private OrderModifyDetailMapper orderModifyDetailMapper;
    @Autowired
    private CmCompanyMapper companyMapper;
    @Resource
    private Producer producer;
    @Autowired
    private SysSiteMapper siteMapper;
    @Autowired
    private OrderPickMapper pickCarMapper;
    @Autowired
    private CmCompanyOrderMapper companyOrderMapper;
    @Autowired
    private FinanceMapper financeMapper;
    @Autowired
    private FinanceDetailMapper financeDetailMapper;
    @Autowired
    private OrderCarVerifyMapper orderCarVerifyMapper;

    @Override
    public PageResult<OrderPick> page(OrderPickParam orderPickParam) {

        // 构造条件
        LambdaQueryWrapper<OrderPick> queryWrapper = new LambdaQueryWrapper<>();

        // 查询分页结果
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<OrderPick> list(OrderPickParam orderPickParam) {

        // 构造条件
        LambdaQueryWrapper<OrderPick> queryWrapper = new LambdaQueryWrapper<>();

        return this.list(queryWrapper);
    }

    @Override
    public void add(OrderPickParam orderPickParam) {

        // 将dto转为实体
        OrderPick orderPick = new OrderPick();
        BeanUtil.copyProperties(orderPickParam, orderPick);

        this.save(orderPick);
    }

    @Override
    public void delete(OrderPickParam orderPickParam) {
        this.removeById(orderPickParam.getId());
    }

    @Override
    public void edit(OrderPickParam orderPickParam) {

        // 根据id查询实体
        OrderPick orderPick = this.queryOrderPick(orderPickParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(orderPickParam, orderPick);

        this.updateById(orderPick);
    }

    @Override
    public OrderPick detail(OrderPickParam orderPickParam) {
        return this.queryOrderPick(orderPickParam);
    }

    @Override
    public ResponseData getWxWaitPickOrderListPage(PickDTO orderDTO) {
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("os.create_time");
        }
        Page<PkgOrderPick> page = this.baseMapper.getWaiDealOrderList(PageFactory.defaultPage(), orderDTO, businessUtil.getTenantId());
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(page, orderDTO));

    }

    @Override
    public Page<PkgOrderPick> getWaitDealOrderList(PickDTO orderDTO) {
        Page<PkgOrderPick> page = this.baseMapper.getWaiDealOrderList(PageFactory.defaultPage(), orderDTO, businessUtil.getTenantId());
        return page;
    }

    @Override
    public PkgOrderPick getWaitDealOrderDetailList(PickDTO orderDTO) {
        PkgOrderPick pick = this.baseMapper.getWaiDealOrderDetailList(orderDTO.getOrderId());
        return pick;
    }

    @Override
    public Map<String, List<String>> getStartCodeAndDestinationCode(PickDTO orderDTO) {
        Map map = new HashMap();
        List<String> startCodes = this.baseMapper.getStartCodes(orderDTO, businessUtil.getTenantId());
        List<String> destinationCodes = this.baseMapper.getDestinationCodes(orderDTO, businessUtil.getTenantId());
        map.put("startCodes", startCodes);
        map.put("destinationCodes", destinationCodes);
        return map;
    }

    @Override
    public Page<PkgOrderPick> getFinishOrderList(PickDTO orderDTO) {
        return this.baseMapper.getFinishOrderList(PageFactory.defaultPage(), orderDTO, businessUtil.getTenantId());
    }

    @Override
    public PkgOrderPick billOfLadingGeneration(PickRecordContractVO orderDTO) {

        return this.baseMapper.billOfLadingGeneration(orderDTO, businessUtil.getTenantId());
    }

    @Override
    public List<PkgOrderPick> getWaitPickExcludeList(PickCarExcludeDTO pickCarExcludeDTO) {
        return this.baseMapper.getWaitPickExcludeList(pickCarExcludeDTO, businessUtil.getTenantId());
    }

    @Override
    public boolean checkMultiAssign(OrderPick orderPick, StringBuilder errorMsg) {
        if (orderPick.getPickOrderVOList() == null || orderPick.getPickOrderVOList().size() < 1) {
            errorMsg.append("请至少选择一辆车指派提车");
            return false;
        }
        for (PickOrderVO pov : orderPick.getPickOrderVOList()) {
            // PkgOrderPick order = pickCarMapper.getPkgOrderPickDetail(pov.getOrderId());
            OrderSub order = orderSubMapper.selectById(pov.getOrderId());
            orderPick.setOrderSub(order);
            if (order.getPickType() == PickCarTypeEnum.ZI_SONG_WAND_DIAN.type) {
                errorMsg.append("请注意，" + order.getCarName() + " 该车的提车方式为自送网点，不可指派提车！");
                return false;
            }
            if (order.getStatus() != OrderStatusEnum.NEW_ORDER.status && order.getStatus() != OrderStatusEnum.WAIT_ASSIGN_DRIVER.status) {
                errorMsg.append("请注意，" + order.getCarName() + " 该车状态不可指派提车！");
                return false;
            }
        }
        if (orderPick.getDriverId() == null && StringUtils.isNotBlank(orderPick.getDriverName()) && StringUtils.isNotBlank(orderPick.getDriverPhone())) {
            if (!Validator.isMobile(orderPick.getDriverPhone())) {
                errorMsg.append("司机电话格式错误！");
                return false;
            }
            if (driverMapper.countByPhone(orderPick.getDriverPhone(), null, businessUtil.getTenantId()) > 0) {
                errorMsg.append("已经存在" + orderPick.getDriverPhone() + "司机信息，请从提示中选择");
                return false;
            }
        }
        return true;
    }

    @Override
    public void multiAssign(OrderPick orderPick) {
        orderPick.setSettlementType(orderPick.getSettlementType() == null ? 1 : orderPick.getSettlementType());
        // 结算人 type 1.提车 2.送车
        Map<String, String> map = getSettlementInfo(
                orderPick.getSettlementId().toString(),
                orderPick.getSettlementName(),
                orderPick.getSettlementPhone(),
                orderPick.getSettlementType() == null ? 1 : orderPick.getSettlementType(),
                orderPick.getOrderId() == null ? orderPick.getPickOrderVOList().get(0).getOrderId() : orderPick.getOrderId(),
                1);
        // 指派了司机
        if (BaseUtils.hasAssignDriver(orderPick.getDriverId(), orderPick.getDriverName(), orderPick.getDriverPhone(),
                orderPick.getDriverCardNumber(), orderPick.getLicensePlateNumber())) {
            orderPick.setAssignDriverUser(LoginContextHolder.me().getSysLoginUserId());
            orderPick.setAssignDriverTime(new Date());
            if (orderPick.getDriverId() != null) {
                orderPick.setDriverId(orderPick.getDriverId());
            }
        }
        for (PickOrderVO pov : orderPick.getPickOrderVOList()) {
            orderPick.setOrderId(pov.getOrderId());
            orderPick.setPickCarFee(pov.getCost());
            orderPick.setTenantId(businessUtil.getTenantId());
            // 指派信息保存
            pickCarMapper.insert(orderPick);
            // 供应商订单
            //添加订单状态修改记录
           orderStatusChangeService.saveOrderStatusChange(orderPick.getOrderSub().getStatus(),OrderStatusEnum.WAIT_PICK.status, orderPick.getOrderId(), "提车");

           businessUtil.addMessage(String.format("%s  %s待验车提醒", orderPick.getOrderSub().getCarName(), orderPick.getOrderSub().getVin()), "你有一个待验车订单，请及时处理", orderPick.getOrderSub(), 2);
            // 子订单状态修改
            if (orderPick.getDriverId() == null) {
                // 没有选择司机
                orderSubMapper.updateStatusById(pov.getOrderId(), OrderStatusEnum.WAIT_PICK.status, null);
            } else {
                orderSubMapper.updateStatusById(pov.getOrderId(), OrderStatusEnum.WAIT_PICK.status, null);
            }
            // 供应商订单保存
            // 通讯录订单数据插入
            addCompanyOrder(orderPick);
            // 财务提车数据插入
            if (pov.getCost() != null && pov.getCost().compareTo(BigDecimal.ZERO) > 0) {
                // 只有提车费大于0才需要结算
                Finance finance = financeMapper.selectOne(new QueryWrapper<Finance>().lambda().eq(Finance::getOrderId, pov.getOrderId()));
                finance.setPick(pov.getCost());
                finance.setPickHas(BigDecimal.ZERO);
                finance.setPickUn(pov.getCost());
                finance.setPickSettlementName(map.get("settlementName"));
                finance.setPickSettlementPhone(map.get("settlementPhone"));
                finance.setPickSettlementType(orderPick.getSettlementType());
                finance.setTenantId(businessUtil.getTenantId());
                financeMapper.update(finance, new QueryWrapper<Finance>().lambda().eq(Finance::getOrderId, pov.getOrderId()));
                // 财务明细插入
                FinanceDetail fd = new FinanceDetail();
                fd.setHasSettlement(BigDecimal.ZERO);
                fd.setNeedSettlement(pov.getCost());
                fd.setOrderId(pov.getOrderId());
                fd.setSettlementPhone(map.get("settlementPhone"));
                fd.setSettlementUser(map.get("settlementName"));
                fd.setUnSettlement(pov.getCost());
                fd.setType(FinanceTypeEnum.PICK.type);
                fd.setTenantId(businessUtil.getTenantId());
                fd.setSettlementUserId(Long.valueOf(map.get("settlementId")));
                fd.setSettlementType(orderPick.getSettlementType());
                if(map.get("settlementSiteId")!=null){
                    fd.setSettlementSiteId(Long.valueOf(map.get("settlementSiteId")));
                }
                financeDetailMapper.insert(fd);
            }
            // activemq通知下游业务系统
            producer.sendBonus(BonusTypeEnum.ASSIGN_PICK.type, orderPick.getOrderId(), LoginContextHolder.me().getSysLoginUserId(), null);
        }
       /* //如果跳过验车,直接进行验车操作
        if(orderPick.getSkipCheck()!=null && orderPick.getSkipCheck()==1){
            for(PickOrderVO pickOrder : orderPick.getPickOrderVOList()){
                OrderCarVerify orderCarVerify = new OrderCarVerify();
                orderCarVerify.setOrderId(pickOrder.getOrderId());
                StringBuilder errorMsg = new StringBuilder();
                if (!orderCarVerifyService.checkVerify(orderCarVerify, errorMsg)) {
                    throw new CustomException(errorMsg.toString());
                }
                Long userId = LoginContextHolder.me().getSysLoginUserId();
                orderCarVerifyService.addVerify(userId, orderCarVerify, true);
            }

        }*/


    }

    @Override
    public PkgPick getPickCarDetail(Long orderId) {
        return pickCarMapper.getPkgPickDetail(orderId);
    }

    @Override
    public boolean checkAssignUpdate(OrderPick orderPick, StringBuilder errorMsg) {
        if (orderPick == null || orderPick.getOrderId() == null) {
            errorMsg.append("参数错误，订单ID不能为空");
            return false;
        }

        return true;
    }

    @Override
    public void updateAssign(OrderPick orderPick) {
        OrderPick origin = pickCarMapper.selectOne(new QueryWrapper<OrderPick>().lambda()
                .eq(OrderPick::getOrderId, orderPick.getOrderId()));
        // 是否指派了司机信息
        if (BaseUtils.hasAssignDriver(orderPick.getDriverId(), orderPick.getDriverName(),
                orderPick.getDriverPhone(), orderPick.getDriverCardNumber(), orderPick.getLicensePlateNumber())) {
            // 指派了司机信息，更新指派时间和指派人
            if (origin.getAssignDriverUser() == null) {
                orderPick.setAssignDriverUser(LoginContextHolder.me().getSysLoginUserId());
            }
            if (origin.getAssignDriverTime() == null) {
                orderPick.setAssignDriverTime(new Date());
            }

            // 订单状态修改 如果订单状态为待指派司机
            if (orderSubMapper.getStatusById(orderPick.getOrderId()) == OrderStatusEnum.WAIT_ASSIGN_DRIVER.status) {
                orderSubMapper.updateStatusById(orderPick.getOrderId(), OrderStatusEnum.WAIT_PICK.status, null);
            }
        }
        // 最后更新orderPick
        pickCarMapper.update(orderPick, new QueryWrapper<OrderPick>().lambda().eq(OrderPick::getOrderId, orderPick.getOrderId()));
        // 企业通讯录订单信息更新
        CmCompanyOrder companyOrder = companyOrderMapper.getByOrderIdAndType(orderPick.getOrderId(), 2);
        if (companyOrder != null) {
            // 编辑
            companyOrder.setCompanyId(orderPick.getCompanyId());
            companyOrder.setLinkmanId(orderPick.getSettlementId());
            companyOrder.setDriverName(orderPick.getDriverName());
            companyOrder.setDriverPhone(orderPick.getDriverPhone());
            companyOrder.setFee(orderPick.getPickCarFee());
            companyOrderMapper.updateById(companyOrder);
        }
        // 订单修改明细
        try {
            addOrderModifyDetail(orderPick, origin);
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }

    }

    @Override
    public OrderCarVerify getOrderCarVerifyByOrderId(Long orderId) {
        OrderCarVerify ocv = orderCarVerifyMapper.selectOne(new QueryWrapper<OrderCarVerify>().lambda()
                .eq(OrderCarVerify::getOrderId, orderId));
        if (ocv != null) {
            ocv.setValidateImages(orderCarVerifyMapper.getVerifyImage(1, ocv.getId()));
            ocv.setDamagedImages(orderCarVerifyMapper.getVerifyImage(2, ocv.getId()));
        }
        return ocv;
    }

    @Override
    public boolean checkPickFree(Long orderId, StringBuilder errorMsg) {
        OrderSub orderSub = orderSubMapper.selectById(orderId);
        if (orderSub.getStatus() != OrderStatusEnum.NEW_ORDER.status || orderSub.getPickType() != PickCarTypeEnum.MIAN_FEE_TI_DUAN.type) {
            errorMsg.append("当前订单状态不可不免提短");
            return false;
        }
        return true;
    }

    @Override
    public void orderPickFree(Long orderId) {

        // 免费提短记录
        OrderPickFree opf = new OrderPickFree();
        opf.setOrderId(orderId);
        opf.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        opf.setTenantId(businessUtil.getTenantId());
        orderPickFreeMapper.insert(opf);
        OrderPick orderPick = new OrderPick();

        orderPick.setOrderId(Long.valueOf(orderId));
        // 免费提短
        orderPick.setType(4);
        orderPick.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        orderPick.setTenantId(businessUtil.getTenantId());
        pickCarMapper.insert(orderPick);
        //添加订单修改记录
        OrderSub orderSub = orderSubService.getById(orderId);
        OrderStatusChange orderStatusChange = new OrderStatusChange();
        orderStatusChange.setBeforeChangeStatus(orderSub.getStatus());
        orderStatusChange.setAfterChangeStatus(OrderStatusEnum.WAIT_PICK.status);
        orderStatusChange.setOrderId(orderId);
        orderStatusChange.setRemark("免费提短");
        orderStatusChangeService.save(orderStatusChange);

        businessUtil.addMessage(String.format("%s  %s待验车提醒", orderSub.getCarName(), orderSub.getVin()), "你有一个待验车订单，请及时处理", orderSub, 2);


        // 订单状态修改
        orderSubMapper.updateStatusById(orderId, OrderStatusEnum.WAIT_PICK.status, OrderStatusEnum.NEW_ORDER.status);
        // activemq通知下游业务
        // producer.sendBonus(BonusTypeEnum.FREE_PICK_CAR.type, orderId, SecurityUtil.getCurrentUserId());
    }

    @Override
    public void pickCarStock(Long orderId) {
        orderSubMapper.updateStatusById(orderId, OrderStatusEnum.NOT_DEPART_ORDER.status, OrderStatusEnum.PICK_SIGNED.status);
        OrderStock stock = new OrderStock();
        stock.setOrderId(Long.valueOf(orderId));
        stock.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        stock.setTenantId(LoginContextHolder.me().getSysLoginUserId());
        orderStockMapper.insert(stock);
        // activemq通知下游业务
        OrderBonus orderBonus = new OrderBonus();
        orderBonus.setOrderId(Long.valueOf(orderId));
        orderBonus.setType(BonusTypeEnum.STOCK.type);
        orderBonus.setUserId(LoginContextHolder.me().getSysLoginUserId());
        producer.sendBonus(BonusTypeEnum.STOCK.type, Long.valueOf(orderId), LoginContextHolder.me().getSysLoginUserId(), null);
    }

    @Override
    public boolean checkMultiPickFree(Long[] orderIds, StringBuilder errorMsg) {
        if (orderIds == null || orderIds.length == 0) {
            errorMsg.append("至少选择一个订单！");
            return false;
        }
        return true;
    }


    @Override
    public Map<String, String> getSettlementInfo(Long settlementId, String settlementName, String settlementPhone, Integer settlementType, Long orderId, Integer type) {
        Map<String, String> map = new HashMap<>();
        map.put("settlementId", settlementId.toString());
        map.put("settlementName", settlementName);
        map.put("settlementPhone", settlementPhone);
        if (settlementType == 2) {
            // 网点垫付
            OrderSub os = orderSubMapper.selectById(orderId);
            SysSite site = siteMapper.selectOne(new QueryWrapper<SysSite>().lambda().eq(SysSite::getTenantId, businessUtil.getTenantId()).eq(SysSite::getRegionCode, type == 1 ? os.getStartCode() : os.getDestinationCode())
                    .and(wrapper -> wrapper.eq(SysSite::getHasDelete, 0)));
            if (site != null) {
                map.put("settlementId", LoginContextHolder.me().getSysLoginUserId().toString());
                map.put("settlementName", LoginContextHolder.me().getSysLoginUser().getName());
                map.put("settlementPhone",  LoginContextHolder.me().getSysLoginUser().getPhone());
                if(businessUtil.getSiteId()!=null){
                    map.put("settlementSiteId",  businessUtil.getSiteId().toString());
                }


            }
        }
        return map;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void returnMultiAssign(Long orderId) {

        //获取订单回退前的状态
        OrderStatusChange statusChange = orderStatusChangeService.getOne(new QueryWrapper<OrderStatusChange>().lambda()
                .eq(OrderStatusChange::getOrderId, orderId)
                .orderByDesc(BaseEntity::getCreateTime)
                .last("limit 1"));

        if (statusChange == null) {
            if(!"提车".equals(statusChange.getRemark())||!"免费提短".equals(statusChange.getRemark())){
                throw new CustomException("当前订单不存在提车状态不可以回退");
            }
        }
            String value = OrderStatusEnum.getValue(statusChange.getBeforeChangeStatus());
            //修改订单状态
            orderSubMapper.updateStatusById(orderId, statusChange.getBeforeChangeStatus(), null);
            //删除提车牵连的财务以外的数据
            companyOrderMapper.delete(new QueryWrapper<CmCompanyOrder>().lambda().eq(CmCompanyOrder::getOrderId, orderId));
            // 最后一次接单时间更新
            // 删除免费提短记录
            orderPickFreeMapper.delete(new QueryWrapper<OrderPickFree>().lambda().eq(OrderPickFree::getOrderId, orderId));
            pickCarMapper.delete(new QueryWrapper<OrderPick>().lambda().eq(OrderPick::getOrderId, orderId));
            //添加修改记录
            OrderModifyDetail orderModifyDetail = new OrderModifyDetail();
            orderModifyDetail.setOrderId(orderId);
            orderModifyDetail.setColumn("status");
            orderModifyDetail.setOldValue(value);
            orderModifyDetail.setValue(OrderStatusEnum.WAIT_PICK.desc);
            orderModifyDetailMapper.insert(orderModifyDetail);
            //删除状态记录
            orderStatusChangeService.removeById(statusChange.getId());


    }

    private void addOrderModifyDetail(OrderPick now, OrderPick origin) throws Exception {
        Long orderId = origin.getOrderId();
        Long userId = LoginContextHolder.me().getSysLoginUserId();
        List<OrderModifyDetail> list = new ArrayList<>();
        if (BaseUtils.neCompareTwo(now.getCompany(), origin.getCompany())) {
            list.add(new OrderModifyDetail(orderId, null,
                    "company", "提车公司名称", now.getCompany(), origin.getCompany(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getSettlementName(), origin.getSettlementName())) {
            list.add(new OrderModifyDetail(orderId, null,
                    "settlement_name", "提车结算人", now.getSettlementName(), origin.getSettlementName(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getSettlementPhone(), origin.getSettlementPhone())) {
            list.add(new OrderModifyDetail(orderId, null,
                    "settlement_phone", "提车结算人电话", now.getSettlementPhone(), origin.getSettlementPhone(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getSettlementType(), origin.getSettlementType())) {
            list.add(new OrderModifyDetail(orderId, null, "settlement_type",
                    "提车结算方式", SettlementTypeEnum.getValue(now.getSettlementType()), SettlementTypeEnum.getValue(origin.getSettlementType()), userId));
        }
        if (BaseUtils.neCompareTwo(now.getDriverName(), origin.getDriverName())) {
            list.add(new OrderModifyDetail(orderId, null, "driver_name", "提车司机姓名",
                    now.getDriverName(), origin.getDriverName(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getDriverPhone(), origin.getDriverPhone())) {
            list.add(new OrderModifyDetail(orderId, null, "driver_phone", "提车司机电话",
                    now.getDriverPhone(), origin.getDriverPhone(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getLicensePlateNumber(), origin.getLicensePlateNumber())) {
            list.add(new OrderModifyDetail(orderId, null, "license_plate_number", "提车小板车牌",
                    now.getLicensePlateNumber(), origin.getLicensePlateNumber(), userId));
        }
        if (BaseUtils.neCompareTwo(now.getDriverCardNumber(), origin.getDriverCardNumber())) {
            list.add(new OrderModifyDetail(orderId, null, "driver_card_number", "提车司机身份证",
                    now.getDriverCardNumber(), origin.getDriverCardNumber(), userId));
        }
        // 结算人修改，需要修改财务相关表
        if (BaseUtils.neCompareTwo(now.getSettlementId(), origin.getSettlementId())) {
            financeMapper.updatePickSettlementInfoByOrderId(origin.getOrderId().toString(), now.getSettlementName(), now.getSettlementPhone());
            financeDetailMapper.updateSettlementUserInfo(origin.getOrderId(), FinanceTypeEnum.PICK.type, now.getSettlementName(), now.getSettlementPhone(), now.getSettlementId());
        }
        if (!BaseUtils.compareDecimal(now.getPickCarFee(), origin.getPickCarFee())) {
            list.add(new OrderModifyDetail(orderId, null, "pick_car_fee", "提车费",
                    BaseUtils.objectToString(now.getPickCarFee()), BaseUtils.objectToString(origin.getPickCarFee()), userId));
            try {
                orderSubService.modifyOrderFeeDetail(orderId, FinanceTypeEnum.PICK.type, now.getPickCarFee(), origin.getPickCarFee(),
                        now.getSettlementId(), now.getSettlementName(), now.getSettlementPhone());
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }
        }
        if (list.size() > 0) {
            for (OrderModifyDetail omd : list) {
                omd.setTenantId(businessUtil.getTenantId());
                orderModifyDetailMapper.insert(omd);
            }
        }
    }


    /**
     * 获取提车记录表
     *
     * @author yujie
     * @since 2023/05/09 17:16
     */
    private OrderPick queryOrderPick(OrderPickParam orderPickParam) {
        OrderPick orderPick = this.getById(orderPickParam.getId());
        if (ObjectUtil.isEmpty(orderPick)) {
            throw new ServiceException(OrderPickExceptionEnum.NOT_EXISTED);
        }
        return orderPick;
    }

    public Map<String, String> getSettlementInfo(String settlementId, String settlementName, String settlementPhone, Integer settlementType, Long orderId, Integer type) {
        Map<String, String> map = new HashMap<>();
        map.put("settlementId", settlementId);
        map.put("settlementName", settlementName);
        map.put("settlementPhone", settlementPhone);
        if (settlementType == 2) {
            // 网点垫付
            OrderSub os = orderSubMapper.selectById(orderId);
            SysSite site = siteMapper.selectOne(new QueryWrapper<SysSite>().lambda()
                    .eq(SysSite::getTenantId, businessUtil.getTenantId())
                    .eq(SysSite::getRegionCode, type == 1 ? os.getStartCode() : os.getDestinationCode())
                    .and(wrapper -> wrapper.eq(SysSite::getHasDelete, 0)));
            if (site != null) {
                map.put("settlementId", LoginContextHolder.me().getSysLoginUserId().toString());
                map.put("settlementSiteId", site.getId().toString());
                map.put("settlementName", site.getName());
                map.put("settlementPhone", LoginContextHolder.me().getSysLoginUser().getPhone() == null ? "暂未设置" : LoginContextHolder.me().getSysLoginUser().getPhone());
            }
        }
        return map;
    }

    private void addCompanyOrder(OrderPick orderPick) {
        CmCompanyOrder companyOrder = new CmCompanyOrder();
        companyOrder.setOrderId(orderPick.getOrderId());
        companyOrder.setType(2);
        companyOrder.setFee(orderPick.getPickCarFee());
        companyOrder.setCompanyId(orderPick.getCompanyId());
        companyOrder.setLinkmanId(orderPick.getSettlementId());
        companyOrder.setAssignUser(LoginContextHolder.me().getSysLoginUserId());
        companyOrder.setAssignTime(new Date());
        companyOrder.setTenantId(businessUtil.getTenantId());
        companyOrder.setDriverName(orderPick.getDriverName());
        companyOrder.setDriverPhone(orderPick.getDriverPhone());
        companyOrderMapper.insert(companyOrder);
        // 最后一次接单时间更新
        linkmanMapper.updateLastTransportTime(orderPick.getSettlementId());
        companyMapper.updateLastTransportTime(orderPick.getCompanyId());
    }


}